package com.javasm.mingming.login.phone;

import com.javasm.mingming.adminuser.entity.AdminUser;
import com.javasm.mingming.common.RedisKeys;
import com.javasm.mingming.common.utils.TokenUtil;
import com.javasm.mingming.login.entity.LoginUserDetails;
import com.javasm.mingming.login.service.impl.PhoneUserDetailsService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.security.Key;

/**
 * @author javasm
 * @version 0.1
 * @className PhoneProvider
 * @descriptioin:
 * @date 2025/1/13 15:02
 * @since jdk11
 */
@Component
public class PhoneProvider implements AuthenticationProvider {
    //org.springframework.security.authentication.AuthenticationProvider
    @Resource
    RedisTemplate<String,Object> redisTemplate;
    @Resource(name = "phoneUserDetailsService")
    UserDetailsService userDetailsService;
    @Resource
    HttpServletResponse response;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取 手机号  验证码
        String phone = (String) authentication.getPrincipal();
        String code = (String) authentication.getCredentials();
        //判断验证码是否正确
        String key = String.format(RedisKeys.User_Phone_Code,phone);
        Object o = redisTemplate.opsForValue().get(key);
        if (o == null){
            throw new BadCredentialsException("验证码过期");
        }
        String realCode = (String) o;
        if (!realCode.equals(code)){
            throw new BadCredentialsException("验证码错误");
        }
        //验证码正确,可以查询用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(phone);
        //删除已经使用过的验证码
        //redisTemplate.delete(key);
        //生成Token
        if (userDetails != null){
            LoginUserDetails loginUserDetails = (LoginUserDetails) userDetails;
            AdminUser adminUser = loginUserDetails.getAdminUser();
            Long uid = adminUser.getUid();
            String jwtStr = TokenUtil.generateToken(uid.toString());
            response.setHeader(TokenUtil.Server_Token_Key,jwtStr);
            response.setHeader("Access-Control-Expose-Header",TokenUtil.Server_Token_Key);
        }
        PhoneToken newPhoneToken = new PhoneToken(userDetails);
        return newPhoneToken;
    }

    //判断,当前的Provider 处理 哪个Authentication对象
    @Override
    public boolean supports(Class<?> aClass) {
        return PhoneToken.class.isAssignableFrom(aClass);
    }



}
